<?php

namespace app\admin\controller;

use app\common\model\RegSourceModel;
use app\common\model\StatPrivateChatLogModel;
use app\common\Esclient;
use app\common\model\ChatStatisticsModel;
use app\common\model\PrivateChatHistoryModel;
use app\common\model\PrivateChatSessionModel;
use app\common\model\UserLevelRuleModel;
use app\common\model\UserModel;
use app\common\model\TransitStatModel;
use app\common\model\PrivateChatBanModel;
use app\service\GatewayWorkerService;
use app\service\PrivatechatService;
use gogrpc\TencentTimServer;
use itbdw\Ip\IpLocation;
use think\facade\Cache;
use think\Db;
use think\db\Query;
use think\facade\Request;
use think\Validate;


/**
 * 私聊模块
 * @date 2022-11-21
 */
class PrivatechatController extends BaseController
{

    /**
     * 私聊列表
     * @return mixed
     */
    //    public function index()
    //    {
    //        $result = PrivatechatService::getPrivateList();
    //        if (Request::isAjax()) {
    //            return json($result);
    //        }
    //        $this->assign('list', $result['list']);
    //        $this->assign('count', count($result['list']));
    //        return $this->fetch();
    //    }

    /**
     * 私聊详情
     * @return mixed
     */
    public function chat_info()
    {
        $anchors = PrivatechatService::getAnchorsInfo($this->admin_id);
        $specialAnchors = PrivatechatService::getSpecialAnchors($this->admin_id);
        $specialAnchorIds = PrivatechatService::getSpecialAnchorIds($this->admin_id);
        $privateChatUploadApi = getConfigPub()->third_upload;
        return $this->assign([
            'specialAnchors' => $specialAnchors,
            'specialAnchorsCount' => count($specialAnchors),
            'anchors' => $anchors,
            'private_chat_ws' => getConfigPub()->private_chat_ws,
            'admin_id' => $this->admin_id,
            'specialAnchorIds' => json_encode($specialAnchorIds),
            'privateChatUploadApi' => $privateChatUploadApi,
        ])->fetch();
    }


    /**
     * 获取聊天内容
     */
    public function get_chat_content()
    {
        $anchor_id = Request::get('anchor_id', 0);
        $conversation_id = Request::get('session_id', "");
        $chat_session = PrivatechatService::getFromConversation($anchor_id, $conversation_id);
        $page = (int)$this->get('page', 1);
        $time = (int)$this->get('time');
        $limit = 30;
        if (count($chat_session) == 0) {
            return json(['list' => [], 'code' => 0, 'session_id' => "", "flag" => 1]);
        }

        // $list[] = [
        //     "session_id" => 1,
        //     "user_id" => $chat_session["UserId"],
        //     "anchor_id" => $anchor_id,
        //     "sender_uid" => 1,
        //     "receive_uid" => 2,
        //     "content" => "121212",
        //     "send_time" => 1,
        //     "img_url" => isset($item['img_url']) ? $item['img_url'] : "",
        // ];
        // return json(['list' => $list, 'code' => 0, 'session_id' => "", "flag" => 1]);

        $conversationId = isset($chat_session["ConversationId"]) ? $chat_session["ConversationId"] : "";
        if (empty($conversationId)) {
            return json(['list' => [], 'code' => 0, 'session_id' => $conversationId, "flag" => 2]);
        }
        try {
            $options = [
                'index' => 'private_history',
                'from' => ($page - 1) * $limit,
                'size' => $limit,
                'where' => [
                    ['session_id.keyword', "=", $conversationId]
                ],
                'sort' => ['send_time' => 'desc']
            ];
            if ($time) {
                $options['where'][] = ['send_time', "<", $time];
            }
            // 获取数据
            $es_client = new Esclient();
            $response = $es_client->search($options,true);

            $data = $response['data'];

            if (empty($data)) {
                return json(['list' => [], 'code' => 0, 'session_id' => $conversationId, "flag" => 3]);
            }
            foreach ($data as &$item) {
                $item['_source']['_id'] = $item['_id'];
            }
            $data = array_column($data, '_source');
            // 如果是倒序，数组翻转
            $data = array_reverse($data);

            $list = [];
            foreach ($data as $item) {
                $list[] = [
                    "id" => $item['_id'],
                    "session_id" => $conversationId,
                    "user_id" => $chat_session["UserId"],
                    "anchor_id" => $anchor_id,
                    "sender_uid" => $item['sender_uid'],
                    "receive_uid" => $item['receive_uid'],
                    "content" => htmlspecialchars($item['content']),
                    "send_time" => $item['send_time'],
                    "img_url" => isset($item['img_url']) ? $item['img_url'] : "",
                ];
                unset($item);
            }
            unset($data, $user_list, $user_ids, $response);
            PrivatechatService::alreadyRead($anchor_id, $conversationId);
            return json(['list' => $list, 'code' => 0, 'session_id' => $conversationId, "flag" => 4]);
        } catch (\Exception $e) {
            var_dump($e->getMessage());
        }
        return json(['list' => [], 'code' => 0, 'session_id' => $conversationId, "flag" => 5]);
    }

    /**
     * 发送聊天内容
     * @return \think\response\Json
     */
    public function send_chat()
    {
        $all_param = Request::param();

        $validate = new Validate([
            'content' => 'require|length:1,300',
            'group_id' => 'require|number',
            'msg_type' => 'require|number',
        ], [
            "content" => "私聊内容在1-300个字符",
            "session_id" => "会话参数错误",
            "group_id" => "'group_id不能为空",
            "msg_type" => "消息类型不能为空"
        ]);

        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }
        // 获取单条基本信息
        $chat_session = PrivatechatService::getFromConversation($all_param["group_id"], $all_param["session_id"]);
        if (count($chat_session) == 0) {
            return parent::bulidFail('私聊会话不存在');
        }
        // 权限判断
        $check_chat_admin = PrivatechatService::checkAdminChat($this->userinfo->roleid, $this->admin_id, $all_param["group_id"]);
        if ($check_chat_admin['code'] != 0) {
            return parent::bulidFail('你当前没有权限回复该用户聊天');
        }

        // $chat_history = $chat_session->chat_history;
        // 调取grpc
        $tim_server = new TencentTimServer();

        $data = [
            "session_id" => $chat_session['ConversationId'],
            "user_id" => (string)$chat_session['UserId'],
            "anchor_id" => $all_param['group_id'],
            "sender_uid" => $all_param['group_id'],
            "receive_uid" => $chat_session['UserId'],
            "content" => "",
            "img_url" => "",
            "send_time" => getMicrotime(),
        ];

        if ($all_param['msg_type'] == 1) {
            $data['content'] = $all_param['content'];
        } else if ($all_param['msg_type'] == 2) {
            $data['img_url'] = $all_param['content'];
        }

        $tim_res = $tim_server->customRelpy($all_param["group_id"], $chat_session['ConversationId'], $data['content'], $data['img_url']);
        if (!$tim_res) {
            return json(['list' => [], 'code' => 1, 'msg' => '发送失败',]);
        }

        //私聊统计

        GatewayWorkerService::sendMsg('say', $data);

        return json(['list' => $data, 'code' => 0, 'msg' => '']);
    }

    public function mult_start_chat()
    {
        $this->assign('ids', Request::param("ids"));
        $this->assign('all', Request::param('all'));
        return $this->fetch();
    }

    public function mult_send_chat()
    {
        $params = Request::param();

        if ($params['all'] == 1) {
            $tim_server = new TencentTimServer();
            $y = $tim_server->BatchCustomReply($params['content'], [], $params['all']);
            return $y ? json(['data' => null, 'code' => 0, 'msg' => '发送成功'])
                : json(['data' => null, 'code' => 0, 'msg' => '发送失败']);
        }

        if ($params['ids'] == '') {
            return parent::bulidFail('发送失败');
        }

        $ids = explode(',', $params['ids']);
        if (count($ids) == 0) {
            return parent::bulidFail('发送失败');
        }
        $ids = array_filter($ids);

        $users = [];
        for ($i = 0; $i < count($ids); $i++) {
            $set = explode('|', $ids[$i]);
            if (count($set) == 0) {
                return parent::bulidFail('发送失败');
            }

            if ($set[0] == '' || $set[1] == '') {
                return parent::bulidFail('发送失败');
            }

            $r = new \Proto\BatchCustomUser;
            $r->setAnchorId($set[0]);
            $r->setUserId($set[1]);
            $r->setName($set[2]);
            $r->setPlatform(@intval($set[3]));

            $users[] = $r;


            $data = [
                "session_id" => 0,
                "user_id" => (string)$set[1],
                "anchor_id" => $set[0],
                "sender_uid" => $set[0],
                "receive_uid" => $set[1],
                "content" => $params['content'],
                "send_time" => getMicrotime(),
            ];
            // GatewayWorkerService::sendMsg('say', $data);
        }

        $tim_server = new TencentTimServer();

        $tim_server->BatchCustomReply($params['content'], $users, $params['all']);
        return json(['data' => null, 'code' => 0, 'msg' => '发送成功']);
    }


    /**
     * 禁言用户
     * @return \think\response\Json
     */
    public function band_user()
    {
        $session_id = Request::post('session_id', 0, 'intval');
        $time = Request::post('time');
        if ($session_id < 1 || !is_numeric($time)) {
            return parent::bulidFail('参数错误，请刷新重试');
        }
        // 获取单条信息
        $session_info = PrivateChatSessionModel::get($session_id);
        if (empty($session_info)) {
            return parent::bulidFail('私聊会话不存在');
        }

        $chat_history_info = PrivateChatHistoryModel::where('id', $session_info->private_chat_history_id)->find();
        if (empty($chat_history_info)) {
            return parent::bulidFail('私聊会话不存在');
        }

        // 权限判断
        $check_chat_admin = PrivatechatService::checkAdminChat($this->userinfo->roleid, $this->admin_id, $session_info->anchor_id);
        if ($check_chat_admin['code'] != 0) {
            return parent::bulidFail('你当前没有权限');
        }

        try {
            $cache_obj = Cache::store('redis');
            $r_key = "PRIVATECHAT:BAN:{$session_info->anchor_id}{$session_info->user_id}";
            if ($time > 0) {
                $res = $cache_obj->set($r_key, $time, $time * 60);
            } else {
                $res = redis_del($r_key);
            }
            if ($res) {
                return parent::bulidSuccess();
            }
        } catch (\Exception $e) {
            return parent::bulidDataFail(['error' => $e->getMessage()], '操作失败，请稍后重试');
        }

        return parent::bulidFail();
    }


    /**
     * 在线设备
     */
    public function device()
    {
        if ($this->request->isAjax()) {
            $page = (int)$this->get('page', 1);
            $where = [
                'index' => 'online_device',
                'size' => $limit = (int)$this->get('limit', 20),
                'from' => ($page - 1) * $limit,
                'where' => [],
                'sort' => ['last_online_time' => 'desc']
            ];

            if (in_array($platform = $this->get('platform'), ['0', '1', '2'])) {
                $where['where'][] = ['platform', '=', $platform];
            }

            if (in_array($level = $this->get('level'), UserLevelRuleModel::column('level'))) {
                $where['where'][] = ['user_level', '=', $level];
            }

            if (ctype_digit($user_id = $this->get('user_id'))) {
                $where['where'][] = ['user_id', '=', $user_id];
            }

            if ($this->userinfo->roleid !== 1 && $this->userinfo->roleid !== 11) {
                if (!$room_ids = PrivatechatService::getChatUserIds($this->admin_id)) {
                    return json([
                        'count' => 0,
                        'list' => [],
                        'code' => 0,
                    ]);
                }

                $where['where'][] = ['room_id', 'IN', $room_ids];
            }

            if ($nickname = trim($this->get('nickname', ''))) {
                $where['where'][] = ['nickname', '=', $nickname];
                $where['where'][] = ['nickname', 'LIKE', $nickname . "%"];
            }

            if ($last_online_time = strtotime($this->get('last_online_time', ''))) {
                $where['where'][] = ['last_online_time', '>=', $last_online_time];
            } else {
                $where['where'][] = ['last_online_time', '>=', time() - 600];
            }

            if ($room_id = $this->get('room_id')) {
                $where['where'][] = ['room_id', '=', $room_id];
            }

            $list = (new Esclient())->search($where);
            foreach ($list['data'] as &$value) {
                if (!empty($value['last_online_time'])) {
                    $value['last_online_time'] = date('Y-m-d H:i:s', $value['last_online_time']);
                } else {
                    $value['last_online_time'] = '-';
                }
            }
            return json([
                'count' => $list['total'],
                'list' => $list['data'],
                'code' => 0,
            ]);
        }
        return $this->assign([
            'level' => UserLevelRuleModel::column('level')
        ])->fetch();
    }

    /**
     * 私聊历史
     */
    public function history()
    {
        if ($this->request->isAjax()) {
            $model = PrivateChatHistoryModel::field('*');
            if (ctype_digit($anchor_id = $this->get('anchor_id', ''))) {
                $model = $model->where('anchor_id', $anchor_id);
            }

            if ($anchor_name = trim($this->get('anchor_name', ''))) {
                $model = $model->where('anchor_name', $anchor_name);
            }

            if (($start_time = strtotime($this->get('start_time', ''))) && ($end_time = strtotime($this->get('end_time', '')))) {
                $model = $model->whereBetween('start_time', [date('Y-m-d H:i:s', $start_time), date('Y-m-d H:i:s', $end_time)]);
            } elseif ($start_time) {
                $model = $model->whereBetween('start_time', [date('Y-m-d H:i:s', $start_time), date('Y-m-d H:i:s')]);
            }

            return json([
                'count' => $model->count('id'),
                'list' => $model->order('id', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()
                    ->toArray(),
                'code' => 0,
            ]);
        }
        return $this->fetch();
    }

    /**
     * 会话列表
     */
    public function chat_user()
    {
        if (!ctype_digit($id = $this->get('id', ''))) {
            return static::bulidFail('ID非法');
        }
        if (!$model = PrivateChatHistoryModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的私聊信息');
        }
        if ($this->request->isAjax()) {
            $model = PrivateChatSessionModel::field('*')->where('private_chat_history_id', $model->id);
            return json([
                'count' => $model->count('id'),
                'list' => $model->with([
                    'user' => function (Query $query) {
                        $query->field('id,nick_name');
                    },
                    'admin' => function (Query $query) {
                        $query->field('id,name');
                    },
                ])
                    ->order('id', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()->each(function ($query) {
                        if ($query->user_id) {
                            $query->user_id = strval($query->user_id);
                        }
                    })
                    ->toArray(),
                'code' => 0,
            ]);
        }
        return $this->assign(['model' => $model])->fetch();
    }

    /**
     * 私聊内容
     */
    public function chat_content()
    {
        if (!ctype_digit($id = $this->get('id', ''))) {
            return static::bulidFail('ID非法');
        }
        if (!$model = PrivateChatSessionModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的私聊信息');
        }
        if ($this->request->isAjax()) {
            $page = (int)$this->post('page', 1);
            $where = [
                'index' => 'private_history',
                'size' => $limit = (int)$this->get('limit', 20),
                'from' => ($page - 1) * $limit,
                'where' => [
                    ['session_id', '=', $model->id]
                ],
                'sort' => ['send_time' => 'desc']
            ];

            $list = (new Esclient())->search($where);
            $nick_names = UserModel::whereIn('id', array_column($list['data'], 'sender_uid'))->column('nick_name', 'id');
            foreach ($list['data'] as &$value) {
                $value['nick_name'] = $nick_names[$value['sender_uid']] ?? $value['sender_uid'];
                $value['send_time'] = date('Y-m-d H:i:s', bcdiv($value['send_time'], '1000', 0));
            }
            return json([
                'count' => $list['total'],
                'pageCount' => ceil($list['total'] / $limit),
                'list' => $list['data'],
                'code' => 0,
                'page' => $page,
            ]);
        }
        return $this->assign(['model' => $model])->fetch();
    }

    public function info()
    {
        return $this->fetch();
    }

    // 私聊列表(新接口)
    public function getPrivateChatList()
    {
        $anchorId = $this->get('anchorid', '');
        echo json_encode($this->privateChatList($anchorId));
    }

    function privateChatList($anchorId)
    {
        $limit = 100;
        if (in_array($anchorId, ['g1', 'g2', 'g3'])) {
            $specialAnchorIds = PrivatechatService::getSpecialAnchorIds($this->admin_id);
            if (!$specialAnchorIds[$anchorId]) {
                return [];
            }
            foreach ($specialAnchorIds[$anchorId] as $k => $uid) {
                $unreadAnchorIds[] = PrivatechatService::getSpecifyAnchorSessionUnread($uid);
            }
        } else {
            $unreadAnchorIds[] = PrivatechatService::getSpecifyAnchorSessionUnread($anchorId);  //[id=>unread]
        }
        $i = 0;
        $resultUnreadSort = [];
        foreach ($unreadAnchorIds as $k => $v) {
            $anchor = PrivatechatService::getUserInfo($v['anchorId']);
            if (!$anchor) {
                continue;
            }
            //$onlieUserIds = PrivatechatService::getOnlineUser($anchor['id']);
            //优先得到所有主播未读的用户对应的未读数
            $sessionUnreadParts = PrivatechatService::getAnchorSessionUnreadParts($v['anchorId'], $limit);
            foreach ($sessionUnreadParts as $cid => $unread) {
                $converSation = PrivatechatService::getFromConversation($v['anchorId'], $cid);
                if (!isset($converSation['ReplyFlag'])) {
                    continue;
                }
                if (!$converSation['ReplyFlag']) { //没有回复过的排除
                    continue;
                }
                $resultUnreadSort[$i] = PrivatechatService::processConverSation($converSation, $unread, $anchor);
                $i++;
            }
            //再取主播未读的用户对应的未读数
            $converSations = PrivatechatService::getAnchorConversations($v['anchorId'], $limit - count($resultUnreadSort));
            foreach ($converSations as $converSation) {
                $found = false;
                foreach ($resultUnreadSort as $v) {
                    if ($v["ConversationId"] == $converSation["ConversationId"]) {
                        $found = true;
                        break;
                    }
                }
                if (!$found) {
                    if (!$converSation['ReplyFlag']) { //没有回复过的排除
                        continue;
                    }
                    $resultUnreadSort[$i] = PrivatechatService::processConverSation($converSation, 0, $anchor);
                    $i++;
                }
            }
        }
        if ($resultUnreadSort) {
            $resultUnread = array_column($resultUnreadSort, '_LatestMsgTime');
            array_multisort($resultUnread, SORT_DESC, $resultUnreadSort);
        }
        return $resultUnreadSort;
    }


    public function stat()
    {
        return $this->fetch();
    }

    public function ajax_stat()
    {
        // $params = Request::param();
        $list = [];
        $count = ChatStatisticsModel::count();
        $list = ChatStatisticsModel::page($this->get('page', 1), $this->get('limit', 20))->select();
        if (count($list) > 0) {
            foreach ($list as &$item) {
                $item['time'] = date("Y-m-d", $item['ctime']);
            }
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }

        return self::bulidFail("未查询到相关数据");
    }

    public function qrcode()
    {
        return $this->fetch();
    }

    public function gen_qrcode()
    {
        $url = Request::param("link");
        $url = base64_encode($url);

        $cache = Cache::store('redis')->handler();

        $uniqid = uniqid();

        $cache->set("transit-link:" . $uniqid, $url, 24 * 60 * 60 * 7);

        $transit = "https://jump.syyacheng.xyz/index.html?gen=" . $uniqid;

        return json(["code" => 0, "msg" => "", "data" => $transit]);
    }

    public function qrcode_stat()
    {
        $this->fetch();
    }

    public function ajax_qrcode_stat()
    {
        $count = TransitStatModel::count();
        if ($count == 0) {
            return self::bulidFail("未查询到相关数据");
        }
        $list = TransitStatModel::order("id", "desc")->page($this->get('page', 1), $this->get('limit', 20))->select();
        return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
    }

    public function private_chat_ban()
    {
        $user_id = Request::param("user_id");
        $count = PrivateChatBanModel::where("user_id", $user_id)->count();
        if ($count > 0) {
            PrivateChatBanModel::where("user_id", $user_id)->delete();
            return parent::bulidSuccess(['btn' => "禁言", "ban" => 0]);
        } else {
            $pc = new PrivateChatBanModel;
            $pc->user_id = $user_id;
            $pc->created_at = date("Y-m-d H:i:s", time());
            $pc->save();
            return parent::bulidSuccess(['btn' => "除解禁言", "ban" => 1]);
        }
    }

    public function del_private_chat()
    {
        $id = Request::param("id");
        $sid = Request::param("sid");
        $send_id = Request::param("send_id");
        $content = Request::param("content");
        $es_index = 'private_history';
        // 查询是否存在
        $options = [
            'index' => $es_index,
            'size'  => 1,
            'from'  => 0,
            'where' => [
                ['_id', '=', $id]
            ],
        ];
        $exist   = Esclient::find($options);
        if (empty($exist)) {
            return json(["code" => 0, "msg" => "消息不存在"]);
        }
        $res = Esclient::delete($es_index, $id);
        if (!empty($res)) {
            $tim_server = new TencentTimServer();
            $tim_res = $tim_server->customRelpy($send_id, $sid,"admin_revoke", $id);
            if (!$tim_res) {
                return json(['list' => [], 'code' => 1, 'msg' => '撤回通知失败',]);
            }
            $redis_key = "PRIVATECHAT:CONVERSATION:";
            $cache = Cache::store('redis')->handler();
            $parts = explode('_', $sid);
            $num1 = $parts[1];
            $num2 = $parts[2];
            $content1 = $cache->hGet($redis_key.$num1, $sid);
            $content2 = $cache->hGet($redis_key.$num2, $sid);
            if ($content1){
                $data1 = json_decode($content1,true);
                $data2 = json_decode($content2,true);
                if ($data1['LastetMsgText'] == $content){
                    $data1['LastetMsgText'] = '';
                    $data2['LastetMsgText'] = '';
                    $cache->hSet($redis_key.$num1, $sid,json_encode($data1,256));
                    $cache->hSet($redis_key.$num2, $sid,json_encode($data2,256));
                }
            }
            //GatewayWorkerService::sendMsg('say', $data);
            return json(["code" => 1, "msg" => "已撤回"]);
        }
        return json(["code" => 0, "msg" => "撤回失败"]);
    }


    public function log_stat()
    {

        // 查询昨日
        $y_day               = date('Y-m-d', strtotime('-1 day', strtotime(date("Y-m-d"))));
        $yestorday_count = StatPrivateChatLogModel::where('date', $y_day)->sum('user_count');
        $this->assign('yestorday_count', $yestorday_count);
        //今日
        $today = date("Y-m-d");
        $today_count = StatPrivateChatLogModel::where('date', $today)->sum('user_count');
        $this->assign('today_count', $today_count);
        $field = "source_key,date,max(user_count) as user_count ";
        $list  = StatPrivateChatLogModel::with('regsource')->where('date', $today)
                    ->field($field)
                    ->select();
        $today_source_name = "";
        $today_max_count = 0;
        if(count($list) > 0) {

            $today_max_count = $list[0]["user_count"];
            if($list[0]->regsource){
                $today_source_name = $list[0]->regsource->source_name;
            }
        }
        $this->assign('today_source_name', $today_source_name);
        $this->assign('today_max_count', $today_max_count);

        //上周
        $where = [];
        $start_time = date("Y-m-d",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y")));
        $end_time = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y")));

        $where[] = ['date', '>=', $start_time];
        $where[] = ['date', '<=', $end_time];
        $lastweek_count = StatPrivateChatLogModel::where($where)->sum('user_count');
        $this->assign('lastweek_count', $lastweek_count);



        $now = new \DateTime();
        $last_week = clone $now;
        $last_week->sub(new \DateInterval("P1W"));
        $this->assign('start_time', $last_week->format("Y-m-d"));
        $this->assign('end_time', date("Y-m-d"));

        //本周
        $where = [];
        $start_time = date("Y-m-d",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
        $end_time = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));

        $where[] = ['date', '>=', $start_time];
        $where[] = ['date', '<=', $end_time];
        $thisweek_count = StatPrivateChatLogModel::where( $where)->sum('user_count');
        $this->assign('thisweek_count', $thisweek_count);
        //上月
        $where = [];
        $start_time = date("Y-m-d",mktime(0, 0 , 0,date("m")-1,1,date("Y")));
        $end_time = date("Y-m-d",mktime(23,59,59,date("m") ,0,date("Y")));

        $where[] = ['date', '>=', $start_time];
        $where[] = ['date', '<=', $end_time];
        $lastmonth_count = StatPrivateChatLogModel::where($where)->sum('user_count');
        $this->assign('lastmonth_count', $lastmonth_count);
        //本月
        $where = [];
        $start_time = date("Y-m-d",mktime(0, 0 , 0,date("m"),1,date("Y")));
        $end_time = date("Y-m-d",mktime(23,59,59,date("m"),date("t"),date("Y")));

        $where[] = ['date', '>=', $start_time];
        $where[] = ['date', '<=', $end_time];
        $thismonth_count = StatPrivateChatLogModel::where( $where)->sum('user_count');
        $this->assign('thismonth_count', $thismonth_count);

        return $this->fetch();

    }

    public function ajax_log_stat()
    {

        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        $source_key = Request::param("source_key");
        $source_name = Request::param("source_name");

        $page  = Request::param("page");
        $limit = Request::param("limit");




        $where = [];
        if (empty($start_time)) {
            $now = new \DateTime();
            $last_week = clone $now;
            $last_week->sub(new \DateInterval("P1W"));
            $start_time = $last_week->format("Y-m-d");
        }
        $where[] = ['stat.date', '>=', $start_time];

        if (empty($end_time) ){
            $end_time = date("Y-m-d");
        }
        $where[] = ['stat.date', '<=', $end_time];

        if($source_key) {
            $where[] = ["stat.source_key", "=", trim($source_key)];
        }

        if($source_name) {
            $where[] = ["reg.source_name", "=", trim($source_name)];
        }

        $field = "stat.id,stat.source_key,stat.date,stat.user_count,stat.chat_count,reg.source_name ";
        $list  = StatPrivateChatLogModel::alias("stat")->join('db_reg_source reg', 'reg.source_key = stat.source_key')->where($where)
            ->field($field)
            ->limit(($page - 1) * $limit, $limit)
            ->order("date desc,  chat_count desc")
            ->select();
        $count = 0;
        if(count($list)> 0){
            $count = StatPrivateChatLogModel::alias("stat")->join('db_reg_source reg', 'reg.source_key = stat.source_key')->where($where)->group('stat.source_key')->count();
            foreach ($list as &$item) {
                if($item->regsource){
                    $item->regsource_id = $item->regsource->id ;
                    $item->source_name = $item->regsource->source_name;
                }else{
                    $item->regsource_id = 0 ;
                    $item->source_name = "";
                }
                unset($item->regsource);
            }
        }


        return json(
                [
                    "code" => 0,
                    "msg" => "",
                    "data" => $list,
                    "count" => $count
                ]
             );
    }


}
